package com.kingyea.app.market.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Serializable;
import java.util.HashMap;

/**
 * @author Mr.Lin
 * @version v1.0.0
 * @description 用于json数据规范化 建造者模式 在返回之前加载数据
 * @date Created in 2017/11/9 10:41  modified by abner on 2017-12-28
 */
public class JSONWrap implements Serializable {

    private static final long serialVersionUID = 7247714666080613254L;

    private static final Logger LOGGER = LoggerFactory.getLogger(JSONWrap.class);
    private static JSONWrap jsonWrap;
    /**
     * 数据
     */
    private Object datas;
    /**
     * 信息码
     */
    private String code;
    /**
     * 操作信息
     */
    private String msg;

    public void JSONWrap() {
        this.datas = null;
        this.code = null;
        this.msg = null;
    }

    public Object getDatas() {
        datas = datas == null ? new HashMap<String, Object>() : datas;
        return datas;
    }

    public void setDatas(Object data) {
        this.datas = data;
    }

    public String getMsg() {
        msg = msg == null ? StateCode.getMsg(StateCode.OPERATION_SUCCESS) : msg;
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public String getCode() {
        code = code == null ? StateCode.OPERATION_SUCCESS : code;
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    /**
     * 将清除之前放入的数据,将数据替换为@param datas
     *
     * @param data
     * @return com.kingyea.app.market.utils.JSONWrap
     * @author Mr.Lin
     * @date 2017/11/9 09:50
     */
    public JSONWrap putAllData(Object data) {
        jsonWrap = new JSONWrap();

        jsonWrap.setDatas(JSON.toJSONString(data));
        jsonWrap.setMsg("ok");
        jsonWrap.setCode("1");
        return jsonWrap;
    }

    public JSONObject build() {
        if (jsonWrap == null) {
            jsonWrap = new JSONWrap();
            jsonWrap.setCode(StateCode.OPERATION_SUCCESS);
            jsonWrap.setMsg(StateCode.getMsg(StateCode.OPERATION_SUCCESS));
        }
        return JSON.parseObject(JSON.toJSONString(jsonWrap, SerializerFeature.WriteMapNullValue), JSONObject.class);
    }


}
